if (typeof(console)=='undefined') {
  console=new Object();
  console.log=function(msg){};
};


var T4B = Class.create({});

T4B.Track = Class.create({
  name:'',
  points:[]
});

T4B.Local = Class.create({
  STORE_NAME: 'test-tcx',
  DB_NAME: 'tracks4me-01',
  MAX_TCX_LEN: 3000,
  xmlHandler:[],
  trackListeners:[],
  listTracksListeners:[],

  initialize: function() {
	  if (!window.google || !google.gears) {
      if (confirm("This demo requires Gears to be installed. Install now?")) {
        location.href = "http://code.google.com/apis/gears/install.html";
      }
      return;
    }
    try {
      this.db = google.gears.factory.create('beta.database');
      if (this.db) {
        this.db.open(this.DB_NAME);
        this.migrateDb(this.db);
      };
      this.localServer = google.gears.factory.create('beta.localserver');
      this.store=this.localServer.createStore(this.STORE_NAME);
    } catch (ex) {
      alert('ERROR ' + ex.message+ " Exiting");
      return;
    }
 	  this.track=null;
    var me=this;
	  //$('displayTracks').onclick=function(){me.loadTracks()};
	  $('uploadButton').onclick=function(){me.browse()};
	  $('exportgpx').onclick=function(){me.exportAsGpx()};
    $('exportgpx').disabled=true;
    $('delete_button').onclick=function(){me.deleteTrack()};
    $('delete_button').disabled=true;
	},

  addTrackListeners:function(listener){
    if (!listener.manager) listener.manager=this;
    this.trackListeners[this.trackListeners.length]=listener;
  },

  addListTracksListeners:function(listener){
    if (!listener.manager) listener.manager=this;
    this.listTracksListeners[this.listTracksListeners.length]=listener;
  },

	loadTracks:function() {
	  var tracks=[];
	  var rs = this.db.execute('select id, name, date, distance from tracks order by date(date) desc');
	  while (rs.isValidRow()) {
      var t=new T4B.Track();
      t.id=rs.field(0);
      t.name=rs.field(1);
      t.date=rs.field(2);
      t.distance=rs.field(3);
      tracks[tracks.length]=t;
      rs.next();
	  }
	  rs.close();

    for (var i=0;i<this.listTracksListeners.length;i++){
      this.listTracksListeners[i].listTracksChanged(tracks);
    };
	},

	showTrack:function(id){
    this.clearTrackListeners();
	  Element.update('results_div','');
	  var rs = this.db.execute('select name, date, distance, secs, avgspeed, description, data from tracks where id=?',[id]);
	  if (!rs.isValidRow()) {
			rs.close();
			alert("Track not found");
			return;
	  };
    var track=new T4B.Track();
    this.track=track;
    track.id=id;
	  track.name=rs.field(0);
    track.date=rs.field(1);
    track.distance=rs.field(2);
    track.secs=rs.field(3);
    track.avgSpeed=rs.field(4);
    track.description=rs.field(5);
	  var data=rs.field(6);
	  rs.close();
	  var jsdata=eval("("+data+")");
	  track.points=[];
	  for (var i=0;i<jsdata.lats.length;i++){
      var p={};
      p.lat=jsdata.lats[i];
      p.lng=jsdata.lngs[i];
      p.dist=jsdata.dists[i];
      p.elev=jsdata.alts[i];
      p.secs=jsdata.secs[i];
      track.points[track.points.length]=p;
	  };
    this.updateTrackListeners();
    return false;
	},
  
  deleteTrack:function(){
    var msg="Delete track "+this.track.name+" . Are you sure?";
    if (!confirm(msg)) return;
	  this.db.execute('delete from tracks where id=?',[this.track.id]);
    this.clearTrackListeners();
	  this.loadTracks();
  },

  clearTrackListeners:function(){
    for (var i=0;i<this.trackListeners.length;i++){
      this.trackListeners[i].clear();
    };
    $('exportgpx').disabled=true;
    $('delete_button').disabled=true;
  },

  updateTrackListeners:function(){
    for (var i=0;i<this.trackListeners.length;i++){
      this.trackListeners[i].trackChanged(this.track);
    };
    $('exportgpx').disabled=false;
    $('delete_button').disabled=false;
  },

	browse:function() {
	  var desktop = google.gears.factory.create('beta.desktop');
    var me=this;
	  desktop.openFiles(
		function(files) {
		  for (var i = 0; i < files.length; i++) {
        console.log("capturing... "+files[i].name);
        var url="uploaded.tcx";
        try{
          var blob=files[i].blob;
          var len=(blob.length/1024);
          console.log("len:" +len +" max: "+me.MAX_TCX_LEN);
          if (len>me.MAX_TCX_LEN){
             var msg="Warning! File "+files[i].name + " has size "+ len.toFixed()+ " Kb.\n Processing can be slow. Continue?";
             if (!confirm(msg)) continue;
          };
          me.store.captureBlob(blob,url,"text/xml");
          me.parseXML(url,'tcx');//TODO extension
        } catch(ex){
            alert('ERROR ' + ex.message);
        };
        me.store.remove(url);
		  }
      me.loadTracks();
		},	{ filter: ['.tcx'] }
	  );
	},

	parseXML:function (url,format) {
    var handler=this.xmlHandler[format];
    if (handler==null){
      console.log(format+ " : no handler");
      return;
    }
  	console.log("Parsing url" + url+" "+new Date());

		if (window.XMLHttpRequest)  {
		  xhttp=new XMLHttpRequest();
		} else  {
		  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xhttp.open("GET",url,false);
		xhttp.send("");
		xmlDoc=xhttp.responseXML;
    handler.parse(this,xmlDoc);
	},

  isKeyLoaded:function(key){
    var rs = this.db.execute('select count(*) from tracks where key=?',[key]);
		var ct=0;
		if (rs.isValidRow()) {
      ct=rs.field(0);
		};
		rs.close();
    var loaded=(ct>0);
    if (loaded) console.log(key+" : already loaded");
    return loaded;
  },

  storeTrack:function(t){
    var jsdata=Object.toJSON(t.data);
    this.db.execute('insert into tracks (name, key, date, distance, secs, avgspeed, data) values (?,?,?,?,?,?,?)', [t.key, t.key, t.date, t.dist, t.secs, t.avgspeed, jsdata]);
  },

	exportAsGpx:function(){
	  var blobbuilder = google.gears.factory.create('beta.blobbuilder');
	  var gpxBuilder=new T4B.GpxBuilder();
	  gpxBuilder.build(blobbuilder,this.track.points);
	  var blob=blobbuilder.getAsBlob();
	  this.store.captureBlob(blob,"/my_gpx","text/xml");
	  var s="<a href='/my_gpx' target='_new'>download GPX</a>";
	  Element.update('results_div',s);
	},

	updateTrack:function(track){
    if (track.id!=this.track.id){
      alert('Invalid track!');
      return;
    };
    this.track=track;
	  this.db.execute('update tracks set name=?, description=? where id=?',[track.name, track.description, track.id]);
    this.clearTrackListeners();
	  this.loadTracks();
    this.updateTrackListeners();
	},

  migrateDb:function(db){
    var sql='create table if not exists schema_info (version int)';
    db.execute(sql);
    var rs = db.execute('select max(version) from schema_info');
		var version;
		if (rs.isValidRow()) {
      version=rs.field(0);
		};
		rs.close();
		if (version==null) version=0;
    sql='create table if not exists tracks (ID INTEGER PRIMARY KEY AUTOINCREMENT, name varchar2(50), key varchar2(20), date varchar(10), distance float, secs integer, avgspeed float, description text, data blob)';
    db.execute(sql);
  }

 });


//----
 
 Date.prototype.setISO8601 = function(dString){
	var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;

	//if (dString.toString().match(new RegExp(regexp))) {
	var d = dString.match(new RegExp(regexp));
	var offset = 0;

	this.setUTCDate(1);
	this.setUTCFullYear(parseInt(d[1],10));
	this.setUTCMonth(parseInt(d[3],10) - 1);
	this.setUTCDate(parseInt(d[5],10));
	this.setUTCHours(parseInt(d[7],10));
	this.setUTCMinutes(parseInt(d[9],10));
	this.setUTCSeconds(parseInt(d[11],10));
	if (d[12])
	this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
	else
	this.setUTCMilliseconds(0);
	if (d[13] != 'Z') {
    offset = (d[15] * 60) + parseInt(d[17],10);
    offset *= ((d[14] == '-') ? -1 : 1);
    this.setTime(this.getTime() - offset * 60 * 1000);
	}
	//}
	//else {
	//this.setTime(Date.parse(dString));
	//}
	return this;
};

Date.secs2Date=function(secs){
    var s=secs % 60;
    var m=((secs-s) % 3600)/60;
    var h=((secs-m*60)/3600).toFixed(0);
    return h+":"+m.toPaddedString(2); //+":"+s.toPaddedString(2);
};

